package com.edeweiss.community.servlet;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class RandomCodeServletTest
 */
@WebServlet("/RandomCodeServlet")
public class RandomCodeServlet extends HttpServlet {
	
	private int width=70;
	private int height=26;
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		BufferedImage buffImg=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g=buffImg.createGraphics();
		
		Random random=new Random();
		
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, width, height);
		
		Font font=new Font("Times New Roman", Font.PLAIN,18);
		
		g.setFont(font);
		
		g.setColor(Color.BLACK);
		g.drawRect(0, 0, width-1, height-1);
		
		for (int i = 0; i < 10; i++) {
			int x=random.nextInt(width);
			int y=random.nextInt(height);
			int x1=random.nextInt(10);
			int y1=random.nextInt(10);
			g.drawLine(x, y, x+x1, y+y1);
		}
		
		StringBuffer randomCode=new StringBuffer();
		int red=0,green=0,blue=0;
		java.util.Random rd=new java.util.Random();
		
		int i=0;
		while(i<4){
			String strRand;
			
			String ch=String.valueOf(random.nextInt(10));
			if(i==0){
				if("0".equals(ch)){
				continue;
				}
			}
			if(i>0){
				if(randomCode.indexOf(ch)!=-1){
					continue;
					}
				}
			strRand=ch;
			
			red=random.nextInt(110);
			green=random.nextInt(50);
			blue=random.nextInt(50);
			
			g.setColor(new Color(red,green,blue));
			int pos_y=rd.nextInt(8)+14;
			g.drawString(strRand, 13*i+6, pos_y);
			
			randomCode.append(strRand);
			i++;
			}
			HttpSession session=req.getSession();
			session.setAttribute("randomCode", randomCode.toString());
			resp.setHeader("Prama", "no-cache");
			resp.setHeader("Cache-Control", "no-cache");
			resp.setDateHeader("Expires", 0);
			
			resp.setContentType("image/jpeg");
			
			ServletOutputStream sos=resp.getOutputStream();
			ImageIO.write(buffImg, "jpeg", sos);
			sos.close();
	}
}
